<script lang="ts" setup>
import { ControlsCard, PaginationCard, SearchCard, TableCard } from '@/components/basic/Card'
import { Pagination } from '@/components/basic/Pagination'
import { pcaa } from "area-data"; // 引入省市区
import { h, reactive, ref, toRefs } from 'vue'
import { Api } from '@/api'
import to from '@/utils/awaitTo'
import { EditOutlined, SafetyCertificateOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'

// 配置医院
const FieldNamesHospital = { label: 'hospitalName', value: 'hospitalId', options: 'children' }
// 配置科室
const FieldNamesDepartment = { label: 'classificationName', value: 'classificationId', options: 'children' }
// 配置
const FieldNames = { label: 'name', value: 'id', options: 'children' }
// 配置路径
const windowsURL = `https://open.douyin.com/platform/oauth/connect?client_key=awh3t9s37l434ybj&response_type=code&scope=data.external.item,video.list.bind,video.data.bind,video.search&redirect_uri=`;

// 响应式数据
const formRef = ref()
const queryRef = ref()
const tiktokRef = ref()
const state = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    uniqueName: undefined, // 抖音号
    affiliatedHospitalId: undefined, // 医院
    topicType: undefined, // 科室
    accountType: undefined, // 账号类型
    yunyingId: undefined, //运营人
    commercialAffairsId: undefined, //商务
    channelId: undefined, //渠道
    producerId: undefined, //制作人
    hospitalId: undefined, //医院
    id: '' //id
  },
  list: [], // 表格数据
  total: 0, //总数
  open: false, // 打开
  title: '', //标题
  rules: {
    hospitalId: [{ required: true, message: '请选择医院', trigger: 'change' }],
    yunyingId: [{ required: true, message: '请选择运营人', trigger: 'change' }],
    // commercialAffairsId: [{ required: true, message: '请选择商务', trigger: 'change' }],
    // channelId: [{ required: true, message: '请选择渠道', trigger: 'change' }],
    producerId: [{ required: true, message: '请选择制作人', trigger: 'change' }]
  }, // 规则

  form: {}, // 表单数据
  loading: false, // 表格loading
  sendLoading: false, // 按钮loading
  dataLoading: false, // 数据loading
  authLoading: false, // 授权loading


  tiktokOpen: false, // tiktok弹窗
  authList: [], //过期权限列表
  authTotal: 0, // 过期权限总数量
  authParams: {
    pageNum: 1,
    pageSize: 5,
    uniqueName: ''
  },

  meereenHospitalsList: [], // 医院搜索列表
  hospitalList: [], // 医院列表
  departmentList: [], // 科室列表
  accountList: [], // 账号类型列表
  operateList: [],//运营列表
  commercialAffairsList: [], // 商务
  channelList: [], //渠道
  producerList: [] //制作人
})

const {
  queryParams,
  list,
  total,
  loading,
  open,
  title,
  rules,
  form,
  tiktokOpen,
  authList,
  authTotal,
  sendLoading,
  authParams,
  authLoading,
  meereenHospitalsList,
  hospitalList,
  departmentList,
  accountList,
  operateList,
  dataLoading,
  commercialAffairsList,
  channelList,
  producerList
} = toRefs(state)

// 获取列表
const getList = async () => {
  const [error, data] = await to(Api.tiktok.tiktokList(queryParams.value))
  if (!error) {
    // console.log(data.rows)
    list.value = data.rows
    total.value = Number(data.total)
  }
}

// 搜索事件
const handleQuery = () => {
  getList()
}

// 重置事件
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
  getList()
}

// 修改打开
const handleEdit = async (item) => {
  reset()
  sendLoading.value = true
  const [error, data] = await to(Api.tiktok.tiktokUpdateEcho({ tiktokId: item.id }))
  sendLoading.value = false
  if (!error) {
    title.value = '修改抖音'
    form.value = data
    open.value = true
  }
}

// 提交事件
const handleOk = (formEl) => {
  if (!formEl) return
  formEl.validate().then(async (values) => {
    const params = Object.assign({}, form.value, values)
    loading.value = true
    const [error, data] = await to(Api.tiktok.tiktokEdit(params))
    loading.value = false
    if (!error && data === 1) {
      message.success('修改成功')
      open.value = false
      await getList()
    }
  })
}

// 过期授权
const handleTiktokAuth = () => {
  tiktokOpen.value = true
  title.value = `过期待授权抖音号`
}

// 抖音号提交
const handleTiktok = (formEl) => {
}

// 去授权
const handleAuthorize = () => {
  const url = new URL(window.location.href);
  window.location.href = windowsURL + url.origin + url.pathname;
}

// 重置
const reset = () => {
  form.value = {
    hospitalId: '',
    yunyingId: '',
    commercialAffairsId: '',
    channelId: '',
    producerId: '',
    affiliatedHospitalId: ''
  }
}

// 图表
const columns = [
  {
    title: '抖音号名称',
    dataIndex: 'uniqueName',
    key: 'uniqueName',
    align: 'center',
    width: 200
  },
  {
    title: '粉丝数',
    dataIndex: 'numberOfFans',
    key: 'numberOfFans',
    align: 'center'
  },
  {
    title: '点赞量',
    dataIndex: 'likesNumber',
    key: 'likesNumber',
    align: 'center'
  },
  {
    title: '账号类型',
    dataIndex: 'accountType',
    key: 'accountType',
    align: 'center'
  },
  {
    title: '所属医院',
    dataIndex: 'hospitalName',
    key: 'hospitalName',
    align: 'center'
  },
  {
    title: '所属科室',
    dataIndex: 'department',
    key: 'department',
    align: 'center'
  },
  {
    title: '所在省',
    dataIndex: 'province',
    key: 'province',
    align: 'center'
  },
  {
    title: '运营人',
    dataIndex: 'yunyingName',
    key: 'yunyingName',
    align: 'center'
  },
  {
    title: '商务',
    dataIndex: 'commercialAffairsName',
    key: 'commercialAffairsName',
    align: 'center'
  },
  {
    title: '渠道',
    dataIndex: 'channelName',
    key: 'channelName',
    align: 'center'
  },
  {
    title: '制作人',
    dataIndex: 'producerName',
    key: 'producerName',
    align: 'center'
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    align: 'center'
  }
]

// 获取医院科室数据
const getHospitalDep = async () => {
  const [error, data] = await to(Api.tiktok.tiktokDep({ timer: new Date().getTime() }))
  if (!error) {
    meereenHospitalsList.value = data.meereenHospitals
    departmentList.value = data.meereenClassifications
  }
}

// 账号类型
const getAccountType = async () => {
  const [error, data] = await to(Api.tiktok.tiktokSearchEcho({ timer: new Date().getTime() }))
  if (!error) {
    accountList.value = data.accountType.map((item: string) => {
      return { label: item, value: item }
    }) // 账号类型
  }
}

// 回显列表
const getTiktokEcho = async () => {
  dataLoading.value = true
  const [error, data] = await to(Api.tiktok.tiktokEcho({ timer: new Date().getTime() }))
  dataLoading.value = false
  if (!error) {
    const { channel, commercialAffairs, hospital, yunying, producer } = data
    operateList.value = yunying //运营人
    commercialAffairsList.value = commercialAffairs //商务
    channelList.value = channel //渠道
    producerList.value = producer //制作人
    hospitalList.value = hospital //医院
  }
}

// 过期授权列表
const getTiktokAuth = async () => {
  authLoading.value = true
  const [error, data] = await to(Api.tiktok.tiktokAuthList(authParams.value))
  authLoading.value = false
  if (!error) {
    authList.value = data.rows
    authTotal.value = Number(data.total)
    console.log(data)
  }
}

getList() // 表格数据
getHospitalDep() // 获取医院科室数据
getAccountType() // 获取账号类型数据
getTiktokEcho() // 回显
getTiktokAuth() // 过期授权列表
</script>

<template>
  <div>
    <!-- 搜索 -->
    <SearchCard>
      <a-form ref="queryRef" :model="queryParams" layout="inline">
        <a-form-item class="mt-5" label="抖音号" name="uniqueName">
          <a-input v-model:value="queryParams.uniqueName" class="values-item" placeholder="抖音号名称" />
        </a-form-item>

        <a-form-item class="mt-5" label="医院" name="affiliatedHospitalId">
          <a-select v-model:value="queryParams.affiliatedHospitalId" :fieldNames="FieldNamesHospital"
                    :options="meereenHospitalsList"
                    class="values-item"
                    placeholder="请输入医院" @change="getList" />
        </a-form-item>

        <a-form-item class="mt-5" label="科室" name="topicType">
          <a-select v-model:value="queryParams.topicType" :fieldNames="FieldNamesDepartment" :options="departmentList"
                    class="values-item" placeholder="请输入话题来源" @change="getList" />
        </a-form-item>

        <a-form-item class="mt-5" label="账号类型" name="accountType">
          <a-select v-model:value="queryParams.accountType" :options="accountList" class="values-item"
                    placeholder="请输入话题来源"
                    @change="getList" />
        </a-form-item>

        <a-form-item class="mt-5" label="运营人" name="yunyingId">
          <a-select v-model:value="queryParams.yunyingId" :field-names="FieldNames" :loading="dataLoading"
                    :options="operateList"
                    class="values-item" placeholder="请选择运营人"
                    @change="getList" />
        </a-form-item>

        <a-form-item class="mt-5" label="商务" name="commercialAffairsId">
          <a-select v-model:value="queryParams.commercialAffairsId" :field-names="FieldNames" :loading="dataLoading"
                    :options="commercialAffairsList"
                    class="values-item" placeholder="请选择商务"
                    @change="getList" />
        </a-form-item>

        <a-form-item class="mt-5" label="渠道" name="channelId">
          <a-select v-model:value="queryParams.channelId" :field-names="FieldNames" :loading="dataLoading"
                    :options="channelList"
                    class="values-item" placeholder="请选择渠道" @change="getList" />
        </a-form-item>

        <a-form-item class="mt-5" label="制作人" name="producerId">
          <a-select v-model:value="queryParams.producerId" :field-names="FieldNames" :loading="dataLoading"
                    :options="producerList" class="values-item" placeholder="请选择制作人"
                    @change="getList"></a-select>
        </a-form-item>

        <a-form-item class="mt-5">
          <a-button type="primary" @click="handleQuery">搜索</a-button>
          <a-button style="margin-left: 10px" @click="resetForm(queryRef)">重置</a-button>
        </a-form-item>

      </a-form>
    </SearchCard>

    <!-- 操作 -->
    <ControlsCard>
      <a-button :danger="total > 0" :disabled="total === 0" :icon="h(SafetyCertificateOutlined)" :loading="sendLoading"
                type="primary" @click="handleTiktokAuth">
        过期待授权{{ authTotal > 0 ? `(${authTotal})个` : '' }}
      </a-button>
    </ControlsCard>

    <!-- 表格 -->
    <TableCard>
      <a-table :columns="columns" :dataSource="list" :loading="loading" :pagination="false">
        <template #bodyCell="{ column, text, record }">
          <template v-if="column.dataIndex === 'province'">
            <span>{{ pcaa['86'][text] }}</span>
          </template>

          <template v-if="column.dataIndex === 'operation'">
            <a-space>
              <a-button :icon="h(EditOutlined)" :loading="sendLoading"
                        type="primary" @click="handleEdit(record)">修改
              </a-button>
              <!--              <a-button :icon="h(BarChartOutlined)" danger type="primary">查看排名</a-button>-->
            </a-space>
          </template>
        </template>
      </a-table>
    </TableCard>

    <!-- 分页 -->
    <PaginationCard>
      <Pagination v-model:page-num="queryParams.pageNum" v-model:page-size="queryParams.pageSize" :total="total"
                  @pagination="getList" />
    </PaginationCard>

    <!--  新增修改模态框  -->
    <a-modal v-model:open="open" :ok-button-props="{ loading: loading }" :title="title" @ok="handleOk(formRef)">
      <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">

        <a-form-item label="医院" name="hospitalId">
          <a-select v-model:value="form.hospitalId" :fieldNames="FieldNames" :loading="dataLoading"
                    :options="hospitalList" placeholder="请输入医院" @change="getList" />
        </a-form-item>

        <a-form-item label="运营人" name="yunyingId">
          <a-select v-model:value="form.yunyingId" :field-names="FieldNames" :loading="dataLoading"
                    :options="operateList" placeholder="请选择运营人" />
        </a-form-item>

        <a-form-item label="商务" name="commercialAffairsId">
          <a-select v-model:value="form.commercialAffairsId" :field-names="FieldNames"
                    :loading="dataLoading" :options="commercialAffairsList" placeholder="请选择商务" />
        </a-form-item>

        <a-form-item label="渠道" name="channelId">
          <a-select v-model:value="form.channelId" :field-names="FieldNames" :loading="dataLoading"
                    :options="channelList" placeholder="请选择渠道" />
        </a-form-item>

        <a-form-item label="制作人" name="producerId">
          <a-select v-model:value="form.producerId" :field-names="FieldNames" :loading="dataLoading"
                    :options="producerList" placeholder="请选择制作人"></a-select>
        </a-form-item>
      </a-form>
    </a-modal>


    <!-- 过期授权抖音号 -->
    <a-modal v-model:open="tiktokOpen" :ok-button-props="{ loading: sendLoading }" :title="title"
             width="800px" @ok="handleTiktok(tiktokRef)">

      <a-input v-model:value="authParams.uniqueName" class="my-3" placeholder="搜索抖音号...." allow-clear @keydown="getTiktokAuth" />
      <a-list :data-source="authList" :loading="authLoading" :pagination="false" class="demo-loadmore-list"
              item-layout="horizontal">
        <template #renderItem="{ item }">
          <a-list-item>
            <template #actions>
              <a-space>
                <a-button danger type="text" @click="handleAuthorize">
                  去授权
                </a-button>
              </a-space>
            </template>
            <a-skeleton :loading="!!item.loading" :title="false" active avatar>
              <a-list-item-meta :description="item.id">
                <template #title>
                  <span>{{ item.uniqueName }}</span>
                </template>
                <template #avatar>
                  <a-avatar :src="item.uniqueImg" />
                </template>
              </a-list-item-meta>
            </a-skeleton>
          </a-list-item>
        </template>
      </a-list>

      <PaginationCard>
        <Pagination v-model:page-num="authParams.pageNum" v-model:page-size="authParams.pageSize"
                    :total="authTotal" @pagination="getTiktokAuth" />
      </PaginationCard>
    </a-modal>
  </div>
</template>

<style lang="less" scoped>
.values-item {
  width: 220px;
}
</style>
